﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ServiceTester.ServerRentIt11;


namespace ServiceTester {
    using System.Globalization;

    public partial class frmAdmin : Form {
        public UserSession uSession;

        public RentItClient rClient;
        
        public frmAdmin(frmUserClient fromClient) {
            if (fromClient != null) {
                InitializeComponent();
                uSession = fromClient.uSession;
                rClient = fromClient.rClient;
                cmbLengthMod.SelectedIndex = 2;
                cmbYearMod.SelectedIndex = 2;

                if (cmbPG.Items.Count < 1) {
                    foreach (var pg in Enum.GetValues(typeof(ParentalGuidance))) {
                        cmbPG.Items.Add(pg);
                    }
                    if (cmbPG.Items.Count > 0) cmbPG.SelectedIndex = 0;
                }

                if (cmbLang.Items.Count < 1) {
                    cmbLang.Items.Add("");
                    foreach (var lang in rClient.ListMovieLanguages()) {
                        cmbLang.Items.Add(lang);
                    }
                    cmbLang.SelectedIndex = 0;
                }
            } else {
                throw new ArgumentException("A User Client Form must be specified!");
            }
        }

        private void btnListAllMoviesRefresh_Click(object sender, EventArgs e) {
            btnListAllMoviesRefresh.Enabled = false;

            var res = rClient.ListMovies();

            lwListAllMovies.BeginUpdate();
            lwListAllMovies.Items.Clear();

            if (res != null) {
                foreach (var media in res) {
                    var lvw = new ListViewItem();
                    lvw.Tag = media;
                    lvw.Text = media.Id.ToString();
                    lvw.SubItems.Add(media.Title);
                    lvw.SubItems.Add(media.Year.ToString());
                    lvw.SubItems.Add(media.LengthFormatted);
                    lvw.SubItems.Add(media.Language);
                    lvw.SubItems.Add(media.ParentalGuidance.ToString());
                    lvw.SubItems.Add((media.HighDefinition == XBool.True).ToString());
                    lvw.SubItems.Add(
                        media.ReleaseDate.HasValue ? media.ReleaseDate.Value.ToString("yyyy-MM-dd") : "Unreleased");
                    lwListAllMovies.Items.Add(lvw);
                }
            }
            lwListAllMovies.EndUpdate();

            btnListAllMoviesRefresh.Enabled = true;
        }

        private void btnListAccountsUpdate_Click(object sender, EventArgs e) {
            btnListAccountsUpdate.Enabled = false;

            var users = rClient.ListUsers();
            lwListUsers.BeginUpdate();
            lwListUsers.Items.Clear();
            foreach(var user in users) {
                var lvw = new ListViewItem();
                lvw.Text = user.Id.ToString();
                lvw.SubItems.Add(user.Name);
                lvw.SubItems.Add(user.Birthday.Value.ToString("yyyy-MM-dd"));
                lvw.SubItems.Add(user.Email);
                lvw.SubItems.Add(user.IsAdmin.ToString());
                lwListUsers.Items.Add(lvw);
            }
            lwListUsers.EndUpdate();

            btnListAccountsUpdate.Enabled = true;
        }

        private void btnListAccountsDeleteSelected_Click(object sender, EventArgs e) {
            btnListAccountsDeleteSelected.Enabled = false;

            if(lwListUsers.SelectedItems.Count > 0) {
                var results = new string[lwListUsers.SelectedItems.Count];
                int success = 0;
                for(var i = 0; i < lwListUsers.SelectedItems.Count; i++) {
                    var lvw = lwListUsers.SelectedItems[i];
                    var uid = 0;
                    if(int.TryParse(lvw.Text, out uid) && uid > 0) {
                        var res = rClient.AdminDeleteAccount(uSession, uid);
                        if (res == UserReturnCode.Success) success++;
                        results[i] = "[#" + uid + "] " + lvw.SubItems[2].Text + " : " + res.ToString();
                    }
                }

                MessageBox.Show(
                    String.Join(Environment.NewLine , results),
                    "Results",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                if(success > 0) btnListAccountsUpdate.PerformClick();
            }

            btnListAccountsDeleteSelected.Enabled = true;
        }

        private void btnListAllMoviesShowInfo_Click(object sender, EventArgs e) {
            btnListAllMoviesShowInfo.Enabled = false;

            if (lwListAllMovies.SelectedItems.Count > 0) {
                for (var i = 0; i < lwListAllMovies.SelectedItems.Count; i++) {
                    var lvw = lwListAllMovies.SelectedItems[i];
                    var mid = 0;
                    if (int.TryParse(lvw.Text, out mid) && mid > 0) {
                        var f = new frmMovieInfo(this, mid);
                        f.Show();
                    }
                }
            }
            
            btnListAllMoviesShowInfo.Enabled = true;
        }

        private void btnListAllMoviesDeleteSelected_Click(object sender, EventArgs e) {
            btnListAllMoviesDeleteSelected.Enabled = false;

            if (lwListAllMovies.SelectedItems.Count > 0) {
                var results = new string[lwListAllMovies.SelectedItems.Count];
                int success = 0;
                for (var i = 0; i < lwListAllMovies.SelectedItems.Count; i++) {
                    var lvw = lwListAllMovies.SelectedItems[i];
                    var mid = 0;
                    if (int.TryParse(lvw.Text, out mid) && mid > 0) {
                        var res = rClient.DeleteMovie(uSession, mid);
                        if (res) success++;
                        results[i] = "[#" + mid + "] " + lvw.SubItems[1].Text + " : " + res.ToString();
                    }
                }

                MessageBox.Show(
                    String.Join(Environment.NewLine, results),
                    "Results",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                if (success > 0) btnListAllMoviesRefresh.PerformClick();
            }

            btnListAllMoviesDeleteSelected.Enabled = true;
        }

        private void lwListAllMovies_DoubleClick(object sender, EventArgs e) {
            btnListAllMoviesShowInfo.PerformClick();
        }

        private void btnFetchImdb_Click(object sender, EventArgs e) {
            btnFetchImdb.Enabled = false;

            var imdbId = txtImdbId.Text.Trim();
            if (frmImdbMovie.ValidIMDBId(imdbId)) {
                var frm = new frmImdbMovie(this, imdbId);
                frm.Show();
            }else {
                MessageBox.Show("Invalid iMDB Id", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            btnFetchImdb.Enabled = true;
        }

        private void btnResetSearch_Click(object sender, EventArgs e) {
            txtSearchMovieTitle.Text = "";
            txtSearchImdbId.Text = "";
            txtSearchMovieRelease.Text = "";
            rdbQualityBoth.Checked = true;
            cmbYearMod.SelectedIndex = 2;
            cmbLengthMod.SelectedIndex = 2;
            if (cmbLang.Items.Count > 0) cmbLang.SelectedIndex = 0;
            if (cmbPG.Items.Count > 0) cmbPG.SelectedIndex = 0;
            numLengthMod.Value = 0;
            numSearchMovieLength.Value = 0;
            numSearchMovieYear.Value = 0;
            numYearMod.Value = 0;
            txtSearchMovieTitle.Focus();
            chkSearchAllMustMatch.Checked = false;
        }

        private void btnSearch_Click(object sender, EventArgs e) {
            btnSearch.Enabled = false;

            var ms = new MovieSearchEntry {
                UserID = uSession != null ? uSession.UserId : 0,
                TitleIsPartial = true,
                AllMustMatch = this.chkSearchAllMustMatch.Checked,
                DoNotSaveToSearchHistory = true,
                MovieEntry =
                    new MovieEntry {
                        Title = this.txtSearchMovieTitle.Text,
                        Length = (int)this.numSearchMovieLength.Value,
                        Year = (int)this.numSearchMovieYear.Value,
                        Language = cmbLang.Text,
                        ParentalGuidance = rClient.GetParentalGuidance(cmbPG.Text),
                        HighDefinition =
                            rdbQualityBoth.Checked ? XBool.Ignore : rdbQualityHD.Checked ? XBool.True : XBool.False,
                        ImdbId = txtSearchImdbId.Text
                    }
            };

            DateTime rday;
            if (DateTime.TryParse(txtSearchMovieRelease.Text, out rday)) {
                ms.ReleaseDateSpecification = DateSpecification.Complete;
                ms.MovieEntry.ReleaseDate = rday;
            } else if (DateTime.TryParseExact(txtSearchMovieRelease.Text.Substring(0, 7), "yyyy-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out rday)) {
                ms.ReleaseDateSpecification = DateSpecification.YearMonth;
                ms.MovieEntry.ReleaseDate = rday;
            } else if (DateTime.TryParseExact(txtSearchMovieRelease.Text.Substring(0, 4), "yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out rday)) {
                ms.ReleaseDateSpecification = DateSpecification.Year;
                ms.MovieEntry.ReleaseDate = rday;
            }

            ms.LengthDifferenceDirection = cmbLengthMod.Text == "±"
                                               ? DifferenceDirection.Both
                                               : cmbLengthMod.Text == "+"
                                                     ? DifferenceDirection.Higher
                                                     : DifferenceDirection.Lower;
            ms.YearDifferenceDirection = cmbYearMod.Text == "±"
                                               ? DifferenceDirection.Both
                                               : cmbYearMod.Text == "+"
                                                     ? DifferenceDirection.Higher
                                                     : DifferenceDirection.Lower;
            ms.LengthDifference = (int)numLengthMod.Value;
            ms.YearDifference = (int)numYearMod.Value;

            this.DoSearch(ms);

            btnSearch.Enabled = true;
        }

        private void DoSearch(MovieSearchEntry ms) {
            var res = rClient.SearchMovies(ms);
            lwListAllMovies.BeginUpdate();
            lwListAllMovies.Items.Clear();

            if (res != null) {
                foreach (var media in res) {
                    var lvw = new ListViewItem();
                    lvw.Tag = media;
                    lvw.Text = "" + media.Id;
                    lvw.SubItems.Add(media.Title);
                    lvw.SubItems.Add("" + media.Year);
                    lvw.SubItems.Add(media.LengthFormatted);
                    lvw.SubItems.Add(media.Language);
                    lvw.SubItems.Add(media.ParentalGuidance.ToString());
                    lvw.SubItems.Add("" + (media.HighDefinition == XBool.True));
                    lvw.SubItems.Add(
                        media.ReleaseDate.HasValue ? media.ReleaseDate.Value.ToShortDateString() : "Unreleased");
                    lwListAllMovies.Items.Add(lvw);
                }
            }
            lwListAllMovies.EndUpdate();
        }
    }
}
